<template>
  <div class="scrollable-form">
    <div class="form-wrapper">
      <el-form
         ref="ruleForm"
        :rules="rules"
        :model="formData"
        label-position="left"
        label-width="80px"
        size="medium"
        v-loading="loading"
      >
        <!-- 第一行 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item
              label="中文名"
              :label-width="width"
              class="form-item"
              prop="chineseName"
            >
              <el-input v-model="formData.chineseName" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="拉丁名" :label-width="width" class="form-item" prop="scientificName">
              <el-input v-model="formData.scientificName" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="分布多度描述"
              :label-width="width"
              class="form-item"
            >
              <el-input v-model="formData.distributionAbundanceDescription" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item
              label="经度"
              :label-width="width"
              class="form-item"
            >
              <el-input v-model="formData.longitude" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="纬度"
              :label-width="width"
              class="form-item"
            >
              <el-input v-model="formData.latitude" />
            </el-form-item>
          </el-col>
           <el-col :span="8">
            <el-form-item label="海拔" :label-width="width" class="form-item">
              <el-input v-model="formData.elevation" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行 -->
        <el-row :gutter="20">
         
          <el-col :span="8">
            <el-form-item label="坡度" :label-width="width" class="form-item">
              <el-input v-model="formData.slopeDegree" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="坡位" :label-width="width" class="form-item">
              <el-input v-model="formData.slopePosition" />
            </el-form-item>
          </el-col>
           <el-col :span="8">
            <el-form-item label="坡向" :label-width="width" class="form-item">
              <el-input v-model="formData.slopeDirection" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第四行 -->
        <el-row :gutter="20">
         
          <el-col :span="8">
            <el-form-item label="生境类型" :label-width="width" class="form-item">
              <el-input v-model="formData.habitatType" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="调查日期"
              :label-width="width"
              class="form-item"
            >
             <el-date-picker
                v-model="formData.surveyDate"
                type="datetime"
                placeholder="选择日期和时间"
                style="width: 100%"
              />
             
            </el-form-item>
          </el-col>
           <el-col :span="8">
            <el-form-item
              label="发现时间"
              :label-width="width"
              class="form-item"
            >
            <el-input v-model="formData.discoveryTime" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第五行 -->
        <el-row :gutter="20">
         
          <el-col :span="8">
            <el-form-item
              label="栖息地干扰"
              :label-width="width"
              class="form-item"
            >
              <el-input v-model="formData.habitatDisturbance" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="保护等级"
              :label-width="width"
              class="form-item"
            >
              <el-input v-model="formData.protectionLevel" />
            </el-form-item>
          </el-col>
           <el-col :span="8">
            <el-form-item
              label="发现地址"
              :label-width="width"
              class="form-item"
            >
              <el-input v-model="formData.discoveryAddress" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第六行 -->
        <el-row :gutter="20">
         
          <el-col :span="8">
            <el-form-item label="盟市" :label-width="width" class="form-item">
              <el-input v-model="formData.leagueCity" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="旗县" :label-width="width" class="form-item">
              <el-input v-model="formData.bannerCountyDistrict" />
            </el-form-item>
          </el-col>
            <el-col :span="8">
            <el-form-item
              label="数据来源"
              :label-width="width"
              class="form-item"
            >
              <el-input v-model="formData.dataSource" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第七行 -->
        <el-row :gutter="20">
        
          <el-col :span="8">
            <el-form-item label="观测者" :label-width="width" class="form-item">
              <el-input v-model="formData.observer" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 特征描述单独一行 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item
              label="特征描述"
              :label-width="width"
              class="form-item"
            >
              <el-input
                v-model="formData.speciesCharacteristicsDescription"
                type="textarea"
                :rows="4"
              />
            </el-form-item>
          </el-col>
        </el-row>
          <el-row>
        <el-col :span="24">
          <!-- 在这里添加上传图片 -->
          <el-form-item label="物种照片"  :label-width="width"
              class="form-item">
            <el-upload
              ref="upload"
              class="upload-demo"
              :action="actionUrl"
              :data="{ ydbh: formData.id }"
              :on-success="handleUploadSuccess"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :file-list="fileList"
              :before-upload="beforeFileUpload"
              list-type="picture-card"
              
            >
              <i class="el-icon-plus" />
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="" />
            </el-dialog>
          </el-form-item>
        </el-col>
      </el-row>
         <el-row>
        <el-col :span="24">
          <!-- 在这里添加上传图片 -->
          <el-form-item label="生境照片"  :label-width="width"
              class="form-item">
            <el-upload
              ref="uploadHabitat"
              class="upload-demo"
              :action="actionUrl"
              :data="{ ydbh: formData.id }"
              :on-success="handleUploadSuccess1"
              :on-preview="handlePictureCardPreview1"
              :on-remove="handleRemove1"
              :file-list="fileList1"
              :before-upload="beforeFileUpload"
              list-type="picture-card"
              
            >
              <i class="el-icon-plus" />
            </el-upload>
            <el-dialog :visible.sync="dialogVisible1">
              <img width="100%" :src="dialogImageUrl1" alt="" />
            </el-dialog>
          </el-form-item>
        </el-col>
      </el-row>
      </el-form>
    </div>
    <!-- 页面内容 -->
    <div class="btn" style="text-align: center">
      <!-- 返回按钮 -->
      <el-button style="margin-right: 8px" @click="goBack">返回</el-button>

      <!-- 提交按钮 -->
      <el-button
        type="danger"
        style="background-color: #1890ff; border-color: #1890ff"
        @click="onSubmit('ruleForm')"
      >{{ this.pageTitle }}</el-button>
    </div>
  </div>
</template>

<script>
import commonOper from "../../../../utils/commonOper";
import config from "@/config/config.js";
import { getToken } from '@/utils/auth' ;
export default {
  // 组件逻辑
  name: 'PlantsAdd',
  data() {
    return {
      pageTitle: "新增数据", // 用于展示页面标题
      width: '140px',
      isFormValid: false,
      formData: {
        id:'',
        chineseName: null,
        scientificName: null,
        distributionAbundanceDescription: null,
        longitude: null,
        latitude: null,
        elevation: null,
        slopeDegree: null,
        slopePosition: null,
        slopeDirection: null,
        habitatType: null,
        surveyDate: null,
        discoveryTime: null,
        habitatDisturbance: null,
        protectionLevel: null,
        discoveryAddress: null,
        leagueCity: null,
        bannerCountyDistrict: null,
        dataSource: null,
        observer: null,
        plantPhotoId: null,
        habitatPhotoId: null,
        speciesCharacteristicsDescription: null,
      },
      rules: {
          chineseName: [
            { required: true, message: '请输入中文名', trigger: 'blur' }
          ],
          scientificName: [
            { required: true, message: '请输入学名', trigger: 'blur' }
          ],
      },
      loading:false,
      actionUrl:config.webapiUrl+"rest//uploadpic",
      options: [], // 用于存储层级数据
      filteredData: [], // 所有属数据

      dialogImageUrl: "",
      dialogImageUrl1: "",
      dialogVisible: false,
      dialogVisible1: false,
      // imageNames: [], // 用于存储上传的图片名字
      fileList: [], // 添加这个数据用于存储上传的文件列表
      fileList1: [], // 添加这个数据用于存储上传的文件列表

    }
  },
  mounted() {
    if (!this.$route.query.data) {
      this.pageTitle = '新增数据';
    } else {
      const data = JSON.parse(this.$route.query.data);
      this.formData = data;

            let baseURL = "http://49.232.236.127/wzimg/";
            let pathsArray = [];
            let pathsArray1 = [];

            if(data.plantPhotoId!=null&&data.plantPhotoId.length>0){
              var photoArr = data.plantPhotoId.split(",");// 使用 trim() 移除可能存在的空格
              photoArr.forEach(function(photo) {
              pathsArray.push({name:photo,url:baseURL+photo});
            });
            }
          this.fileList=pathsArray;

          if(data.habitatPhotoId!=null&&data.habitatPhotoId.length>0){
              var photoArr = data.habitatPhotoId.split(",");// 使用 trim() 移除可能存在的空格
              photoArr.forEach(function(photo) {
              pathsArray1.push({name:photo,url:baseURL+photo});
            });
            }
            this.fileList1=pathsArray1;
      this.pageTitle = '修改数据';
    }
  },

  methods: {
    goBack() {
      this.$router.go(-1)
    },

    onSubmit(formName) {
     
      let that = this;
      let surl='';
      let isSubmit=false;
      this.$refs[formName].validate((valid) => {
          if (valid) {
            isSubmit=true;
          }
      });
      //处理照片
      
      let pthtostr="";
      this.fileList.forEach(function(item) {
        if(item.response!=undefined){
           pthtostr+=item.response.data.newFileName+",";
        }else{
           pthtostr+=item.name+",";
        } 
      });
      this.formData.plantPhotoId=pthtostr.slice(0, -1);

      let pthtostr1="";
      this.fileList1.forEach(function(item) {
        if(item.response!=undefined){
           pthtostr1+=item.response.data.newFileName+",";
        }else{
           pthtostr1+=item.name+",";
        } 
      });
      this.formData.habitatPhotoId=pthtostr1.slice(0, -1);

      if(!isSubmit){
        this.$message.error('数据校验错误，中文名和拉丁名不能为空！');
        return;
      }

      if (this.pageTitle === "新增数据") {
        surl=config.webapiUrl+"/nd/plantsurvey/addSurveyPoint";
      } else if (this.pageTitle === "修改数据") {
        surl=config.webapiUrl+"nd/plantsurvey/editSurveyPoint";

      }
      that.loading = true;
      let paramscommo = {
        this: that,
        url: surl,
        headers: {
          Authorization: "Bearer " + getToken(),
        },
        data: that.formData,
        successFunc: function (response) {
          that.loading = false;
          if (response.data.code == 0) {
            that.$message.success("保存成功！");
             // 延迟一下再返回，让用户看到成功提示
            setTimeout(() => {
              this.goBack();
            }, 1000);
          } else {
            let params = {
              this: that,
              title: "提示",
              message: "保存失败，请稍后重试！" + response.data.msg,
              successFunc: function () {},
            };
            commonOper.showWarnAlert(params);
          }
        },
        failFunc: function (response) {
          that.loading = false;
          let params = {
            this: that,
            title: "提示",
            message: "网络异常，请稍后重试！" + response.data.data,
            successFunc: function () {},
          };
          commonOper.showWarnAlert(params);
        },
      };
      commonOper.HttpPost(paramscommo);
    },
    beforeFileUpload(file){
      const isJpgOrPng =
        file.type === "image/jpeg" || file.type === "image/png";
        const isLt2M = file.size / 1024 / 1024 < 50;

        if (!isJpgOrPng) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 50MB!');
        }
        return isJpgOrPng && isLt2M;
    },
    handleRemove(file, fileList) {
      // 处理文件删除逻辑
      this.fileList=fileList;
    },
    handleRemove1(file, fileList) {
      // 处理文件删除逻辑
      this.fileList1=fileList;
    },

    handleUploadSuccess(response, file, fileList) {
      
      if (response.code == -1) {
        this.$message.error(response.msg);
        // 删除重复的文件
        // console.log("delete before:",this.fileList);
        // const index = this.fileList.findIndex(
        //   (item) => item.name === file.name
        // );
        // console.log("index:",index);
        // if (index !== -1) {
        //   this.fileList.splice(index, 1);
        // }
        // console.log("delete after:",this.fileList);
        return;
      }
      this.fileList=fileList;
      this.$message.success("物种图片上传成功");
     
    },

    handleUploadSuccess1(response, file, fileList) {
      
      if (response.code == -1) {
        this.$message.error(response.msg);
        // 删除重复的文件
        // console.log("delete before:",this.fileList);
        // const index = this.fileList.findIndex(
        //   (item) => item.name === file.name
        // );
        // console.log("index:",index);
        // if (index !== -1) {
        //   this.fileList.splice(index, 1);
        // }
        // console.log("delete after:",this.fileList);
        return;
      }
      this.fileList1=fileList;
      this.$message.success("物种图片上传成功");
     
    },
    // 预览图片
    handlePictureCardPreview(file) {
     
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handlePictureCardPreview1(file) {
     
      this.dialogImageUrl1 = file.url;
      this.dialogVisible1 = true;
    },
  }
}
</script>

<style scoped>
.scrollable-form {
  display: flex;
  flex-direction: column;
  height: 90vh; /* 设置高度为视窗高度 */
}

.form-wrapper {
  flex: 1; /* 让表单部分占据剩余空间 */
  overflow-y: auto; /* 设置垂直滚动条 */
  border: 1px solid #ccc;
  padding: 20px;
  border-bottom: none;
}

.form-item {
  border: 1px solid #ccc;
  padding: 10px;
  background-color: #fafafa;
}

.label {
  font-weight: bold;
  text-align: left;
}

.el-input {
  width: 100%;
}

.btn {
  padding: 20px;
  border-top: 1px solid #ccc;
  position: sticky; /* 使按钮固定在底部 */
  bottom: 0; /* 使按钮固定在底部 */
  background-color: #fff; /* 添加背景色，以便在滚动时覆盖表单部分 */
}
</style>
